<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 报价单
 */

class billTemp
{

    private $dbca;

    public function __construct(&$dbca)
    {
        $this->dbca = $dbca;
    }


    /**
     * 查询报价单
     */
    public function searchBillTemp(&$arg_array)
    {
        $sql = '';

        //订单号
        if (isset($arg_array['tempCode']) && !empty($arg_array['tempCode'])) {
            $sql .= " AND bt.tempCode LIKE '%" . trim($arg_array['tempCode']) . "%'";
        }

        if (isset($arg_array['tempName']) && !empty($arg_array['tempName'])) {
            $sql .= " AND bt.tempName LIKE '%" . trim($arg_array['tempName']) . "%'";
        }

        if (isset($arg_array['companyId']) && !empty($arg_array['companyId'])) {
            $sql .= " AND cm.company_id = " . $arg_array['companyId'];
        }

        if (isset($arg_array['companyName']) && !empty($arg_array['companyName'])) {
            $sql .= " AND cm.company_name LIKE '%" . trim($arg_array['companyName']) . "%'";
        }

        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= " AND bc.createTime >= '" . $arg_array['startDate'] . "'";
        }

        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= " AND bc.createTime <= '" . $arg_array['endDate'] . " 23:59:59'";
        }

        if (isset($arg_array['tempStatus']) && !empty($arg_array['tempStatus'])) {
            $sql .= " AND bt.tempStatus IN(" . $arg_array['tempStatus'] . ")";
        }

        if (isset($arg_array['producer']) && !empty($arg_array['producer'])) {
            $sql .= " AND bt.producer = " . $arg_array['producer'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {
            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {
                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_temp bt
                            INNER JOIN company_master cm ON bt.companyId=cm.company_id ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }
                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
                else{
                    $sql .= ' ORDER BY bt.createTime DESC ';
                }

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
            }

            $search_sql = 'SELECT bt.*, cm.company_name,um.trueName,um.mobile AS userMobile,
                          ss.sendTypeName,dt.distribution_technician_name
                          FROM bill_temp bt
                          INNER JOIN company_master cm ON bt.companyId=cm.company_id 
                          LEFT JOIN user_master um ON um.userID = bt.creator
                          LEFT JOIN sys_sendtype ss ON bt.expressId=ss.sendTypeID 
                          LEFT JOIN sys_distribution_technician dt ON bt.producer=dt.distribution_technician_id ' . $sql;
            $item_array = &$this->dbca->stmt_query($search_sql);

            return $item_array;

        } catch (Exception $e) {
            error_log($e->getMessage());
            return null;
        }
    }

    //查看详情
    public function searchTempDtl($code)
    {
        //查询分类信息
        $search_sql = "SELECT * FROM bill_temp_dtl WHERE tempCode = '" . $code . "'";
        $item_array = &$this->dbca->stmt_query($search_sql);
        return $item_array;
    }

    //查看附件
    public function searchAnnex($code)
    {
        $search_sql = "SELECT bta.*,btd.categoryName FROM bill_temp_annex bta
        INNER JOIN bill_temp_dtl btd ON bta.goodsId=btd.goodsId
        WHERE bta.aType=0 AND bta.tempCode = '" . $code . "' ORDER BY btd.goodsId";

        $item_array = &$this->dbca->stmt_query($search_sql);
        return $item_array;
    }

    //修改报价单状态
    public function changeStatus($param)
    {
        $bill_temp = new entity('bill_temp');
        $bill_temp->tempCode = $param['tempCode'];

        if (!$this->dbca->fetch($bill_temp)) {
            return array('code' => 400, 'message' => '未找到小样订单信息');
        }
        //判断操作前的状态是否符合逻辑
        //订单状态 0:创建, 1:审核, 2:制作中, 3:制作完成, 4:已发货, 5:已收货, 9:取消
        if($param['status'] != 9 && $bill_temp->tempStatus != ($param['status']-1)){
            return array('code' => 400, 'message' => '订单状态异常');
        }

        if($param['status'] == 1 || $param['status'] == 9 ) {
            $bill_temp->auditor = $param['operator'];
        }

        //认领
        if($param['status'] == 2) {
            $bill_temp->producer = $param['producer'];
            $bill_temp->producerDate = date('Y-m-d H:i:s');
        }
        //完成
        if($param['status'] == 3) {
            $bill_temp->finshDate = date('Y-m-d H:i:s');
            foreach ( $param['files'] as $goodsId => $item ) {
                foreach ( $item as $num => $fileName){
                    $temp_annex = new entity('bill_temp_annex');
                    if($fileName){
                        $temp_annex->tempCode = $param['tempCode'];
                        $temp_annex->goodsId = $goodsId;
                        $temp_annex->fileName = $fileName.'.jpg';
                        $temp_annex->aType = 0;
                        $this->dbca->save($temp_annex);
                    }else{
                        $temp_annex->annexId = $num;
                        if (!$this->dbca->fetch($temp_annex)) {
                            $this->dbca->delete($temp_annex);
                        }
                    }
                }
            }
        }
        //发货
        if($param['status'] == 4) {
            $bill_temp->sender = $param['sender'];
            $bill_temp->expressNum = $param['expressNum'];
            $bill_temp->sendDate = date('Y-m-d H:i:s');
        }
        //收货
        if($param['status'] == 5) {
            $bill_temp->receivDate = date('Y-m-d H:i:s');
        }

        $bill_temp->tempStatus = $param['status'];
        $this->dbca->save($bill_temp);
        return array('code' => 200, 'data'=>$bill_temp);
    }

    //保存报价单
    public function saveTemp($param)
    {
        $bill_temp = new entity('bill_temp');
        if(isset($param['tempCode']) && !empty($param['tempCode'])){
            $bill_temp->tempCode = $param['tempCode'];
            if(!$this->dbca->fetch($bill_temp)){
                return array('code' => 400, 'message' => '未找到报价单信息');
            }
        }else {
            $bill_temp->tempCode = generate_seqno('seqno_temp', 'T');
            $bill_temp->creator = $param['operator'];
        }

        $bill_temp->tempStatus = 0;
        $bill_temp->companyId = $param['companyId'];
        $bill_temp->tempName = $param['tempName'];
        $bill_temp->area = $param['area'];
        $bill_temp->categoryName = $param['categoryName'];
        $bill_temp->expressId = $param['expressId'];
        $bill_temp->request = $param['request'];
        $bill_temp->requestDate = $param['requestDate'];
        $bill_temp->receiver = $param['receiver'];
        $bill_temp->receivMobile = $param['receivMobile'];
        $bill_temp->province = $param['province'];
        $bill_temp->provinceName = $param['provinceName'];
        $bill_temp->city = $param['city'];
        $bill_temp->cityName = $param['cityName'];
        $bill_temp->county = $param['county'];
        $bill_temp->countyName = $param['countyName'];
        $bill_temp->address = $param['address'];
        $bill_temp->remark = $param['remark'];

        $this->dbca->beginTransaction();

        try{
            $this->dbca->save($bill_temp);
            if(isset($param['tempCode']) && !empty($param['tempCode'])) {
                $this->dbca->stmt_query('DELETE FROM bill_temp_dtl WHERE tempCode = ?', 's', $param['tempCode']);
            }
            foreach ($param['dtl'] as $goods) {
                $dtl = new entity('bill_temp_dtl');
                $dtl->creator = $param['operator'];
                $dtl->tempCode = $bill_temp->tempCode;
                $dtl->categoryId = $goods['goodsCategoryId'];
                $dtl->categoryName = $goods['goodsCategoryName'];
                $dtl->color = $goods['color'];
                $dtl->colorDis = $goods['colorDis'];
                $dtl->make = $goods['make'];
                $dtl->spec = $goods['spec'];
                $dtl->amount = $goods['amount'];
                $dtl->effect = $goods['effect'];
                $dtl->remark = $goods['remark'];
                $this->dbca->save($dtl);
            }
            $this->dbca->commit();
            return array('code' => 200 , 'message' => 'ok');

        }catch (Exception $e){
            elog($e->getMessage());
            $this->dbca->rollBack();
        }
        return array('code' => 500 , 'message' => '系统错误，保存失败');

    }

    //查看详情
    public function searchHisData($param)
    {
        //查询分类信息
        $search_sql = "SELECT bt.tempCode,bt.tempName,btd.categoryName,btd.goodsId,btd.color,btd.colorDis,btd.amount,
                        btd.effect,btd.remark,btd.spec FROM bill_temp bt
                        INNER JOIN bill_temp_dtl btd ON bt.tempCode=btd.tempCode WHERE 1=1 ";
        $search_sql .= ' AND bt.companyId='.$param['companyId'];
        $search_sql .= ' AND btd.categoryId='.$param['categoryId'];
        $search_sql .= ' ORDER BY bt.createTime DESC';
        $item_array = &$this->dbca->stmt_query($search_sql);
        return $item_array;
    }
}